define(function (require, exports, module) {

    var $ = require("lib/zepto");
    var winDialog = require("lib/winDialog");
    // var Guide = require("lib/com/guide");
    var Player = require("lib/com/player");
    var Util = require("lib/com/util");
    var Dialog = require("./dialog");

    var CLS_ON = 'on';
    var CLS_LUCK = 'luck';
    var CLS_SNOWER = 'snower';

    var TPL_COIN = '<div style="top: {top}; left: {left}; -webkit-animation: fade {t1} {t2}, drop {t1} {t2};">\
				<img src="{url}" style="-webkit-animation: counterclockwiseSpinAndFlip {t5};width:{width}; max-width:{maxHeight}">\
				</div>';

    var gPlayerTop = 0;
    var timer = null;
    var TIMEOUT_DIALOG = 2000;

    /**
     * 砸金蛋
     * @constructor
     */
    function Egg() {
        this.rendered = false;
        // this.mustFollow = APP.mustFollow && !APP.followed;

        this.render();
    }
    Egg.prototype = {
        constructor: Egg,
        // 渲染
        render: function () {
            var _self = this;
            if (!_self.rendered) {
                _self._init();

                _self.rendered = true;
            }
        },
        // 初始化
        _init: function () {
            var _self = this,
                adHeight = 0,
                classes = ['one', 'two', 'three'];

            // 播放器
            _self.player = $('#J_Player');
            // 广告
            _self.ad = $(".ad");
            // 金蛋
            _self.shape = $("#J_Shape");
            // 延迟transform，解决QQ浏览器经常变形问题。
            _self.shape.children().each(function(index, el) {
                $(el).addClass(classes[index]);
            });
            // 锤子
            _self.hit = $("#J_Hit");
            // 锤子音乐
            _self.hitAudio = $('#J_HitAudio')[0];

            // 音乐播放
            if (_self.player.length) {
                _self.player = new Player(_self.player.selector);
                gPlayerTop = parseInt(_self.player.container.css("top"));
            }
			
            _self._bindUI();
            // 对话框
            _self.dialog = new Dialog("#J_Dialog",_self.pass,CLS_SNOWER);

            adHeight = _self.ad.height();
            if (adHeight > 0) {
                _self.player.container && _self.player.container.css("top", adHeight);
            }

            // 关注引导页Mask
            // if (_self.mustFollow) {
                // _self.followMask = _self.createDomByClass("ui-mask");
                // _self.followPage = new Guide("follow"); // 关注页
            // }

        },
        // 绑定事件
        _bindUI: function () {
            var _self = this;

            // 砸蛋
            _self.pass=new pass(function () {
				 _self._handleEggClick();
            // _self.shape.delegate("span", "click", function (e) {
                // var point = parseFloat(APP.point) || 0;
                // if (point > 0) { // 消耗积分提示
                    // confirm("兑换将消耗" + point + "积分，你确定兑换？", {
                        // clickFn: function(conEvent) {
                            // this.destroy();
                            // // 确认按钮
                            // if ($(conEvent.target).parent().index() == 1) {
                                // _self._handleEggClick();
                            // }
                        // }
                    // });
                // } else {
                    // _self._handleEggClick();
                // }
            });

            // 广告关闭
            _self.ad.find(".ad-close").click(function () {
                _self.ad.hide();
                _self.player.container && _self.player.container.css("top", gPlayerTop);
                // 记忆广告关闭状态
                sessionStorage.setItem("adClosed", true);
            });

            // 关注
            // if (_self.followMask) {
                // _self.followMask.click(function () {
                    // _self.followPage.show();
                // });
            // }

            // 中奖纪录
            $('.win-table').delegate("input", "click", function (e) {
                _self._handleWinTable(e.currentTarget);
            });
			
			//锦囊内的奖章列表
            // $('#awardInfo').delegate("input", "click", function (e) {
                // _self._handleWinTable(e.currentTarget);
            // });
			
            // 领取任务
            $('.mission').on("click", function (e) {
                _self._handleMission(e.currentTarget);
            });
        },
        _handleEggClick: function() {
            var _self = this;
            if (_self.shape.find('.'+ CLS_ON).length) {
                return false;
            }

            // var egg = $(e.currentTarget);
            // 中和移动设备的声音延迟播放效果
            _self._handleEgg();
            setTimeout(function() {
                // egg.toggleClass(CLS_ON);
                _self.hitAudio && _self.hitAudio.play();
            }, 800);

            // 显示锤子
            // _self.hit.addClass(CLS_ON).css({left: e.pageX, top: e.pageY});
            // // 隐藏锤子
            // timer && clearTimeout(timer);
            // timer = setTimeout(function () {
            //     _self.hit.removeClass(CLS_ON);
            // }, 1500);
        },
        // 处理砸蛋
        _handleEgg: function () {
            var _self = this,
                // egg = $(egg),
                dialog = _self.dialog;
            $.getJSON(APP.urls.win+"&eid="+APP.eid,false, function (data) {
                data = data || {};
				if(APP.chance>0){APP.chance --;}
				$("#J_Times").text(APP.chance);
                switch (data.success) {
                    case 1: // 中奖
					//中奖后应在$('.win-table')增加一个奖品，并绑定动作
						var tmp="";
						tmp+="<tr><td>"+data.actiontime+"</td>";
						tmp+="<td>"+data.giftname+"</td>";
						var params="";
						if(data.cardno){
							params+=" data-cardno=\""+data.cardno+"\"";
							params+=" data-secret=\""+data.secret+"\"";
						}
						params+=" value=\"领取"+data.gtype_name+"\"";
						params+=" data-mygid=\""+data.mygid+"\"";
						params+=" data-gid=\""+data.gid+"\"";
						params+=" data-gtype=\""+data.gtype_code+"\"";
						params+=" data-getway=\""+data.getway+"\"";
						tmp+="<td><input type=\"button\" class=\"js-myg"+data.mygid+"\" "+params +" /></td></tr>";
						$(tmp).delegate("input", "click", function (e) {
							_self._handleWinTable(e.currentTarget);
						});
						$(".win-table").prepend(tmp);
						
						var tmp="";
						tmp+='<div class="codeInfoBox">';
						tmp+='<div class="djqImgBox"><img src="'+data.giftpic+'_200x200.jpg"/></div>';
						tmp+='<div class="isEmptyAward ellipsis">'+data.giftname+'</div>';
						//<!--div class="codeperiod" style="margin: 0.25rem 0.6rem;"><span>兑奖期限</span>：2016.07.20 至 2016.07.27</div-->
						//tmp+='<div class="goDetailIcon">'+medal[m].get_time+'</div>';
						tmp+='<div class="awardWrap"></div>';
						
						var params="";
						if(data.cardno){
							params+=" data-cardno=\""+data.cardno+"\"";
							params+=" data-secret=\""+data.secret+"\"";
						}
						params+=" value=\"领取"+data.gtype_name+"\"";
						params+=" data-mygid=\""+data.mygid+"\"";
						params+=" data-gid=\""+data.gid+"\"";
						params+=" data-gtype=\""+data.gtype_code+"\"";
						params+=" data-getway=\""+data.getway+"\"";
						
						tmp+="<div class=\"buttons\"><input type=\"button\" class=\"js-myg"+data.mygid+"\" "+params +" /></div>";
						tmp+='</div>';
						$("#giftAward").prepend(tmp);
						
                        _self.pass.play(true);
                        // egg.toggleClass(CLS_LUCK);
                        _self._fallCoin();
                        setTimeout(function() {
                            dialog.renderUI(Dialog.TYPE.take, data);
                        }, TIMEOUT_DIALOG);
                        break;
                    case 2: // 未中奖
                        data.callback = function () {
                            // egg.removeClass(CLS_ON);
                        };
                        _self.pass.play(false);
                        setTimeout(function() {
                            dialog.renderUI(Dialog.TYPE.again, data);
                            // 重置参与次数
                            _self._resetCount(data.remainCount);
                            _self.pass.reset();
                        }, TIMEOUT_DIALOG);
                        break;
                    case 3: // 天次数用完
                        // egg.removeClass(CLS_ON);
                        _self.hit.removeClass(CLS_ON);
                        _self.pass.play(false);
                        setTimeout(function() {
                            dialog.renderUI(Dialog.TYPE.noDayTimes, data);
                            // 重置参与次数
                            _self.pass.reset();
                            _self._resetCount(data.remainCount);

                        }, TIMEOUT_DIALOG);
                        break;
                    case 4: // 总次数用完
                        // egg.removeClass(CLS_ON);
                        _self.hit.removeClass(CLS_ON);
                        _self.pass.play(false);
                        setTimeout(function() {
                            dialog.renderUI(Dialog.TYPE.noAllTimes, data);
                            // 重置参与次数
                            _self.pass.reset();
                            _self._resetCount(data.remainCount);
                        }, TIMEOUT_DIALOG);
                        break;
                    default: // 异常提示
                        // egg.removeClass(CLS_ON);
                        _self.hit.removeClass(CLS_ON);
                        _self.pass.play(false);
                        setTimeout(function() {
                            dialog.renderUI(Dialog.TYPE.noDayTimes, {title: data.error});
                        }, TIMEOUT_DIALOG);
                }
            });
        },
        // 重置参与次数
        _resetCount: function (num) {
            if (num || num == 0) {
                $('#J_Times').text((+num)||0);
            }
        },
        // 处理中奖记录
        _handleWinTable: function (btn) {
            var _self = this,
                dialog = _self.dialog;

            var btn = $(btn),
                getway = btn.attr("data-getway"),
                gtype = btn.attr("data-gtype"),
                mygid = btn.attr("data-mygid"),
                gid = btn.attr("data-gid"),
                cardno = btn.attr("data-cardno"),
                secret = btn.attr("data-secret"),
                url;
			var options = {"getway": getway, "mygid": mygid, "gid": gid,"cardno":cardno,"secret":secret};
				dialog.renderUiSwitch(options);
        },
		
		//处理领取任务
		_handleMission:function(btn){
            var _self = this,
                dialog = _self.dialog;

            var btn = $(btn),
				mis = btn.attr("data-mis"),
				options = {"mis":mis,"eid":APP.eid};
				switch(mis){
					case "everyday" :
						$.getJSON(APP.urls.mission,options,function(json){
							alert(json.msg);
						});
					break;
					case "sign" :
						var day = new Date();
					    options.curdate = day.getFullYear()+"-"+(day.getMonth()+1)+"-"+day.getDate();
						$.getJSON(APP.urls.mission,options,function(json){
							if(json.hasError){
								alert("抱歉，不能进行签到！"+json.msg);
								return;
							}
							$(".poupFadIn").hide();
							options.signList = json.setting;
							dialog.renderUI(Dialog.TYPE.signDays, options);
						});
					break;
					case "order" :
						$(".poupFadIn").hide();
						dialog.renderUI(Dialog.TYPE.orderChance, options);
					break;
					case "jifen" :
						$.getJSON(APP.urls.mission,options,function(json){
							if(json.setting.onoff_jfdh==1){
								$(".poupFadIn").hide();
								options.setting = json.setting;
								dialog.renderUI(Dialog.TYPE.jifenChance, options);
							}else{
								alert("抱歉！积分兑换功能已关闭。");
							}
						});
					break;
					case "cartadd" :
						$.getJSON(APP.urls.mission,options,function(json){
							$(".poupFadIn").hide();
							dialog.renderUI(Dialog.TYPE.addCartChance, {"cart_items":json.setting,"cart_cfg":json.cart_cfg,"eid":APP.eid});
						});
					break;
				}
		},
        // 飘银元
        _fallCoin: function () {
            var snowsDom = $('.' + CLS_SNOWER),
                img = APP.imgs.coin,
                num = Math.random() * 8 + 7 | 0,
                snows = Array(num).join(",").split(","),
                snowsHTML = "";

            if (!snowsDom.length) {
                snowsHTML = Util.template(TPL_COIN, snows, function () {
                    return {
                        top: "-30px",
                        left: Math.random() * 100 + "%",
                        t1: Math.random() * (8 - 3) + 2 + "s",
                        t2: Math.random() * 2 + "s",
                        t5: Math.random() * (8 - 3) + 2 + "s",
                        url: img,
                        width: Math.round(Math.random() * (38 - 10) + 10) + "px",
                        maxHeight: "43px"
                    };
                });
                snowsDom = $('<div class="' + CLS_SNOWER + '">' + snowsHTML + '</div>');
                $(document.body).append(snowsDom);
            } else {
                snowsDom.show();
            }
        },
        // 创建指定样式名的DOM
        createDomByClass: function (sClass) {
            var jDom = $('.' + sClass);
            if (!jDom.length) {
                jDom = $('<div class="' + sClass + '"></div>');
                $(document.body).append(jDom);
            }

            return jDom;
        }
    };

    module.exports = Egg;
});
